<?php

// Database connection settings
define("PG_DB", "secondtestgis");
define("PG_HOST", "localhost");
define("PG_USER", "postgres");
define("PG_PORT", "5433");
define("TABLE", "ktm_roads01");
define("PG_PWD", "nitesh");

$counter = $pathlength = 0;
/* @var $xml type */


//  $list($start[0],$start[1])=explode(' ',$_REQUEST['startpoint']);
//  $list1($end[0],$end[1])=explode(' ',$_REQUEST['finalpoint']);
// Retrieve start point
$start = explode(' ', $_REQUEST['startpoint']);
$startPoint = array($start[0], $start[1]);

//
//  // Retrieve end point
$end = explode(' ', $_REQUEST['finalpoint']);
$endPoint = array($end[0], $end[1]);

$con = pg_connect("host=" . PG_HOST . " port=" . PG_PORT . " user=" . PG_USER . " password=" . PG_PWD . " dbname=" . PG_DB);
$sql="insert into jpt values(".$start[0].",".$start[1].")";
$query = pg_query($con,$sql);


//------------------------------------------------------------------------------------------------------  
// Find the nearest edge
$startEdge = findNearestEdge($startPoint);
$endEdge = findNearestEdge($endPoint);

// FUNCTION findNearestEdge
function findNearestEdge($lonlat) {

    // Connect to database
    $con = pg_connect("host=" . PG_HOST . " port=" . PG_PORT . " user=" . PG_USER . " password=" . PG_PWD . " dbname=" . PG_DB);

    $sql = "SELECT gid, source, target,the_geom,
                         distance(the_geom, ST_GeometryFromText(
                      'POINT(" . $lonlat[0] . " " . $lonlat[1] . ")',3857)) AS dist
                FROM " .TABLE. " 
                    WHERE ST_DWithin(the_geom, 'SRID=3857;POINT(" . $lonlat[0] . " " . $lonlat[1] . ")', 1000.0)
                ORDER BY dist LIMIT 1";

    $query = pg_query($con, $sql);

    $edge['gid'] = pg_fetch_result($query, 0, 0);
    $edge['source'] = pg_fetch_result($query, 0, 1);
    $edge['target'] = pg_fetch_result($query, 0, 2);
    $edge['the_geom'] = pg_fetch_result($query, 0, 3);

    // Close database connection
    pg_close($con);

    return $edge;
}

//-----------------------------------------------------------------------------------------------------------
// Select the routing algorithm
switch ($_REQUEST['method']) {
    case 'SPD' : // Shortest Path Dijkstra

        $sql = "SELECT rt.gid, AsText(rt.the_geom) AS wkt,
                       length(rt.the_geom) AS length, " . TABLE . ".gid
                    FROM " . TABLE . ",
                        (SELECT gid, the_geom
                            FROM dijkstra_sp_delta(
                                '" . TABLE . "',
                                " . $startEdge['source'] . ",
                                " . $endEdge['target'] . ",
                                3000)
                         ) as rt
                    WHERE " . TABLE . ".gid=rt.gid;";
        break;

//--------------------------------------------------------------------------------------------------------------		  
    case 'SPA' : // Shortest Path A*

        $sql = "SELECT rt.gid, AsText(rt.the_geom) AS wkt,
                         length(rt.the_geom) AS length, " . TABLE . ".gid
                      FROM " . TABLE . ",
                          (SELECT gid, the_geom
                              FROM astar_sp_delta(
                                  '" . TABLE . "',
                                  " . $startEdge['source'] . ",
                                  " . $endEdge['target'] . ",
                                  3000)
                           ) as rt
                      WHERE " . TABLE . ".gid=rt.gid;";
        break;

//-------------------------------------------------------------------------------------------------------------------		  
    case 'SPS' : // Shortest Path Shooting*

        $sql = "SELECT rt.gid, AsText(rt.the_geom) AS wkt,
                         length(rt.the_geom) AS length, " . TABLE . ".gid
                      FROM " . TABLE . ",
                          (SELECT gid, the_geom
                              FROM shootingstar_sp(
                                  '" . TABLE . "',
                                  " . $startEdge['gid'] . ",
                                  " . $endEdge['gid'] . ",
                                  5000, 'length', true, true)
                           ) as rt
                      WHERE " . TABLE . ".gid=rt.gid;";
        break;
} // close switch
// Connect to database

$dbcon = pg_connect("host=" . PG_HOST . " port=" . PG_PORT . " user=" . PG_USER . " password=" . PG_PWD . " dbname=" . PG_DB);

//  $sql1="select status from urban_roads where gid=7";
// Perform database query
$result = pg_query($dbcon, $sql);

//------------------------------------------------------------------------------------------------------------------  
// Return route as XML

$xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>' . "\n";
$xml .= "<route>\n";

// Add edges to XML file
while ($edge = pg_fetch_assoc($result)) {

    $pathlength += $edge['length'];

    $xml .= "\t<edge id='" . ++$counter . "'>\n";
    $xml .= "\t\t<gid>" . $edge['gid'] . "</gid>\n";
    $xml .= "\t\t<wkt>" . $edge['wkt'] . "</wkt>\n";
    $xml .= "\t\t<length>" . round(($pathlength / 1000), 3) . "</length>\n";
    $xml .= "\t</edge>\n";
}

$xml .= "</route>\n";

// Close database connection
pg_close($dbcon);

// Return routing result
header('Content-type: text/xml',true);
echo $xml;
?>